package com.luyuan.crm.member.web.provider;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;

import org.springframework.stereotype.Component;

import com.luyuan.crm.member.model.Region;
import com.luyuan.crm.member.service.RegionService;
import com.ruijie.web.jsf.provider.SelectItemsProvider;
import com.ruijie.util.StringUtils;

@Component("regionProvider")
public class RegionProvider implements SelectItemsProvider {

    @Resource(name = "regionService")
    private RegionService regionService;

    @Override
    public List<SelectItem> getSelectItems(Object... parameters) {
        List<SelectItem> items = new ArrayList<SelectItem>();

        String province = null, city = null;
        UIInput uiInput = (UIInput) FacesContext.getCurrentInstance().getViewRoot().findComponent("userForm:province");
        if (uiInput == null) {
            uiInput = (UIInput) FacesContext.getCurrentInstance().getViewRoot()
                    .findComponent("orderWizard_form:province");
        }
        if (uiInput == null) {
            uiInput = (UIInput) FacesContext.getCurrentInstance().getViewRoot().findComponent("orderForm:province");
        }
        if (uiInput != null) {
            province = (String) uiInput.getValue();
        }

        uiInput = (UIInput) FacesContext.getCurrentInstance().getViewRoot().findComponent("userForm:city");
        if (uiInput == null) {
            uiInput = (UIInput) FacesContext.getCurrentInstance().getViewRoot().findComponent("orderWizard_form:city");
        }
        if (uiInput == null) {
            uiInput = (UIInput) FacesContext.getCurrentInstance().getViewRoot().findComponent("orderForm:city");
        }
        if (uiInput != null) {
            city = (String) uiInput.getValue();
        }

        if (city == null) {
            return items;
        }

        List<Region> regions = regionService.loadRegion(province, city);
        for (Region region : regions) {
            if (StringUtils.isNullOrEmpty(region.getRegion())) {
                continue;
            }

            SelectItem item = new SelectItem(region.getRegion(), region.getRegion());
            items.add(item);
        }

        return items;
    }

}
